﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using UFIDA.U9.Cust.XH.PlugBE.Model;
using UFIDA.U9.Cust.XH.PlugBE.Tool;
using UFSoft.UBF.Business;
using UFSoft.UBF.Eventing;

namespace UFIDA.U9.Cust.XH.PlugBE
{
    /// <summary>
    /// 标准采购：
    /// 采购订单、委外订单
    /// </summary>
    class PurchaseOrderSubmitExtend : IEventSubscriber
    {
        public void Notify(params object[] args)
        {
            #region 从事件参数中取得当前业务实体													 

            if (args == null || args.Length == 0 || !(args[0] is UFSoft.UBF.Business.EntityEvent))
                return;
            BusinessEntity.EntityKey key = ((UFSoft.UBF.Business.EntityEvent)args[0]).EntityKey;
            if (key == null)
                return;
            UFIDA.U9.PM.PO.PurchaseOrder entity = key.GetEntity() as UFIDA.U9.PM.PO.PurchaseOrder;
            if (entity == null)
                return;

            #endregion
            string biztype = UFIDA.U9.Base.Doc.BusinessTypeEnum.EnumRes.GetResource(entity.DocumentType.BusinessType.Name);//业务类型
            //采购订单从提交审核事件
            if (PubWebClass.IsSyncToOA()&&!biztype.Contains("工序外协")&&!biztype.Contains("全程委外") && entity.BusinessDate > PubWebClass.startSysDate && entity.OriginalData.Status == PM.PO.PODOCStatusEnum.Opened && entity.Status == PM.PO.PODOCStatusEnum.Approving)
            {
                POToOA(entity);
            }
        }


        public static void POToOA(UFIDA.U9.PM.PO.PurchaseOrder entity)
        {
            string strbilltype = "采购订单";
            string oatablename = "formtable_main_20_dt1";

            string biztype = UFIDA.U9.Base.Doc.BusinessTypeEnum.EnumRes.GetResource(entity.DocumentType.BusinessType.Name);//业务类型
            if (biztype.Contains("工序外协") || biztype.Contains("全程委外"))
            {
                strbilltype = "外协采购";
                oatablename = "formtable_main_21_dt1";
            }
            else if (biztype.Contains("标准采购"))
            {
                strbilltype = "采购订单";
            }
            else
            {
                //其他业务类型不处理
                return;
            }
            Tool.OAFlowParam OA = new Tool.OAFlowParam();
            //根据不同的组织和单据获取ID信息
            OA.workflowId = Tool.DBHelper.getOAFlowID(entity.Org.Code, strbilltype);
            OA.requestName = strbilltype;
            DataTable dt = Tool.DBHelper.getU9Datatble($" exec proc_getDatabaseTable '{entity.Org.ID}','{entity.ID}','{strbilltype}' ");
            string userId = "";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //创建人编码
                string createcode = dt.Rows[i]["createcode"].ToString();
                userId = PubWebClass.GetOAUserIDByCode(createcode);
                //人员
                string rycode = dt.Rows[i]["cgy"].ToString();
                dt.Rows[i]["cgy"] = PubWebClass.GetOAUserIDByCode(rycode);
                //部门
                string depcode = dt.Rows[i]["bm"].ToString();
                dt.Rows[i]["bm"] = PubWebClass.GetOADepIDByCode(depcode);

                //核算组织
                string orgcode = dt.Rows[i]["hszz"].ToString();
                dt.Rows[i]["hszz"] = PubWebClass.GetOAOrgIDByCode(orgcode);
                //结算组织
                string jszz = dt.Rows[i]["jszz"].ToString();
                dt.Rows[i]["jszz"] = PubWebClass.GetOAOrgIDByCode(jszz);

                //供应商
                string gys = dt.Rows[i]["gys"].ToString();
                dynamic obj = new { gysbm = gys };
                dt.Rows[i]["gys"] = PubWebClass.FindHttp("供应商", OAUrlHelper.findSupplierUrl, OAUrlHelper.userId, obj);

            }
            OA.mainData = Tool.DBHelper.getMainDtTONVList(dt, entity.ID.ToString());
            //处理子表
            DataTable dtc = DBHelper.getU9Datatble($" exec proc_getDatabaseTable '{entity.Org.ID}','{entity.ID}','{strbilltype}行' ");
            for (int i = 0; i < dtc.Rows.Count; i++)
            {
                //项目
                string procode = dtc.Rows[i]["xmbm"]?.ToString();
                if (!string.IsNullOrEmpty(procode))
                {
                    dynamic obj = new { xmbm = procode };
                    dtc.Rows[i]["xmmc"] = PubWebClass.FindHttp("项目", OAUrlHelper.findProjectUrl, OAUrlHelper.userId, obj);
                }
                //收获组织
                string orgcode = dtc.Rows[i]["shzz"].ToString();               
                dtc.Rows[i]["shzz"] = PubWebClass.GetOAOrgIDByCode(orgcode);
            }
            if (string.IsNullOrEmpty(dt.Rows[0]["id"].ToString()))
            {
                OA.detailData = Tool.DBHelper.getChildDtTONVList(dtc, oatablename);
            }
            else
            {
                OA.detailData = Tool.DBHelper.getChildDtTONVList(dtc, oatablename, "1");
            }
            string main = JsonConvert.SerializeObject(OA.mainData);
            string detial = JsonConvert.SerializeObject(OA.detailData);
            if (dt.Rows.Count > 0 && string.IsNullOrEmpty(dt.Rows[0]["id"]?.ToString()))
            {
                string data = $"workflowId={ OA.workflowId}&requestName={OA.requestName }&mainData={ HttpUtility.UrlEncode(main)}&detailData={ HttpUtility.UrlEncode(detial)}";
                OARequestResult oARequestResult = PubWebClass.doCreateRequest(data, userId, strbilltype, $"【{strbilltype}】{main}\r\n\r\n {detial}");
                if (oARequestResult.code.ToLower().Contains("success"))
                {
                    //回写流程号到U9
                    string sql = $"update PM_PurchaseOrder set DescFlexField_PrivateDescSeg1='{oARequestResult.data.requestid}' where id={entity.ID} ";
                    DataSet ds = new DataSet();
                    int result = UFSoft.UBF.Util.DataAccess.DataAccessor.RunSQL(UFSoft.UBF.Util.DataAccess.DataAccessor.GetConn(), sql, null, null, true, out ds);
                }
            }
            else
            {
                //更新接口
                string id = dt.Rows[0]["id"].ToString();
                //OA更新接口
                string data = $"otherParams=save&requestId={id}&requestName={OA.requestName }&mainData={ HttpUtility.UrlEncode(main)}&detailData={ HttpUtility.UrlEncode(detial)}";
                OARequestResult oARequestResult = PubWebClass.submitRequest(data, userId, strbilltype, $"【{strbilltype}】{main}\r\n\r\n {detial}");
            }
        }

    }
}
